package com.wjs.fork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {
    private static final Integer value=10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin,int end){
        this.begin=begin;
        this.end=end;
    }

    @Override
    protected Integer compute() {
        if(end-begin<=value){
            for(int i=begin;i<=end;i++){
                result+=i;
            }
        }else {
            int mid=(begin+end)/2;
            MyTask task1 = new MyTask(begin, mid);
            MyTask task2 = new MyTask(mid + 1, end);
            //拆分
            task1.fork();
            task2.fork();
            //合成
            result=task1.join()+task2.join();
        }
        return result;
    }
}
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(myTask);
        Integer result = submit.get();
        System.out.println(result);
    }
}
